<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('年月')" prop="days">
            <el-date-picker
              v-model="form.days"
              clearable
              style="width: 200px"
              type="month"
              value-format="yyyy-MM"
              :placeholder="$t('年月')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('亮灯分类')" prop="classificationOfLights">
            <dict-select
              v-model="form.classificationOfLights"
              dictionary="classification_of_lights"
              :placeholder="$t('亮灯分类')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('累计土地成本')+ $t('金额单位')" prop="accumulatedLandCost">
            <Money v-model="form.accumulatedLandCost" unit="w" :placeholder="$t('累计土地成本')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('土地成本调整项')+ $t('金额单位')" prop="landCostAdjustmentItem">
            <Money v-model="form.landCostAdjustmentItem" unit="w" :placeholder="$t('土地成本调整项')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('除地价外直接投资')+ $t('金额单位')" prop="additionToLandPrice">
            <Money v-model="form.additionToLandPrice" unit="w" :placeholder="$t('除地价外直接投资')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('累计费用总额')+ $t('金额单位')" prop="totalAccumulatedExpenses">
            <Money v-model="form.totalAccumulatedExpenses" unit="w" :placeholder="$t('累计费用总额')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('累计总成本')+ $t('金额单位')" prop="totalCumulativeCost">
            <Money v-model="form.totalCumulativeCost" unit="w" :placeholder="$t('累计总成本')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('已推盘货值'+ $t('金额单位'))" prop="valueGoodsPushed">
            <Money v-model="form.valueGoodsPushed" unit="w" :placeholder="$t('已推盘货值')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('已推盘套数')" prop="numberSetsPushedDisks">
            <Money v-model="form.numberSetsPushedDisks" :placeholder="$t('已推盘套数')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('已售套数')" prop="soldACycle">
            <Money v-model="form.soldACycle" :placeholder="$t('已售套数')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('本月认购套数')" prop="thisMonthSubscribeCycle">
            <Money v-model="form.thisMonthSubscribeCycle" :placeholder="$t('本月认购套数')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('本月认购均价(元/㎡)')" prop="thisMonthSubscribeAverage">
            <Money v-model="form.thisMonthSubscribeAverage" :placeholder="$t('本月认购均价(元/㎡)')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('已认购总额')+ $t('金额单位')" prop="totalSubscription">
            <Money v-model="form.totalSubscription" unit="w" :placeholder="$t('已认购总额')" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('已签约总额')+ $t('金额单位')" prop="totalContractAmount">
            <Money v-model="form.totalContractAmount" unit="w" :placeholder="$t('已签约总额')" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('累计签约面积(㎡)')" prop="accumulatedContractedArea">
            <Money v-model="form.accumulatedContractedArea" :placeholder="$t('累计签约面积(㎡)')" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('平均签约单价(元/㎡)')" prop="averageContractUnitPrice">
            <Money v-model="form.averageContractUnitPrice" :placeholder="$t('平均签约单价(元/㎡)')" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('累计回笼资金')+ $t('金额单位')" prop="accumulatedRecoveryFunds">
            <Money v-model="form.accumulatedRecoveryFunds" unit="w" :placeholder="$t('累计回笼资金')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('总授信额度')+ $t('金额单位')" prop="totalLineCredit">
            <Money v-model="form.totalLineCredit" unit="w" :placeholder="$t('总授信额度')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('后续售价趋势及对项目收益影响简要分析')" prop="briefAnalysis">
            <el-input v-model="form.briefAnalysis" type="textarea" :placeholder="$t('后续售价趋势及对项目收益影响简要分析')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('红黄灯项目进展')" prop="redAndYellowDeal">
            <el-input v-model="form.redAndYellowDeal" type="textarea" :placeholder="$t('红黄灯项目进展')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('需沟通协调事项')" prop="needCommunicate">
            <el-input v-model="form.needCommunicate" type="textarea" :placeholder="$t('需沟通协调事项')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="list-table">
        <div class="area-header">
          <span class="area-header-title">{{ $t('业态销售明细') }}</span>
        </div>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="addHandleDetail"
            >{{ $t('新增') }}</el-button>
          </el-col>
        </el-row>
        <el-table
          v-loading="loading"
          :data="form.dealMonitoringDetailList"
          border
          tooltip-effect="darkTable"
        >
          <el-table-column :label="$t('序号')" align="center" type="index" width="50" />
          <el-table-column :label="$t('业态类型')" align="center" :prop="typeFormats" :formatter="typeFormatsFormat" />
          <el-table-column :label="$t('累计认购面积(㎡)')" align="center" prop="cumulativeSubscriptionArea" width="180">
            <template slot-scope="scope">
              <span>{{ moneyFormat(scope.row.cumulativeSubscriptionArea) }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('累计认购货值')+ $t('金额单位')" align="center" prop="cumulativeSubscriptionValue" width="180">
            <template slot-scope="scope">
              <span>{{ moneyFormat(scope.row.cumulativeSubscriptionValue, 'w') }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('平均认购单价(元/㎡)')" align="center" prop="averageSubscriptionPrice" width="180">
            <template slot-scope="scope">
              <span>{{ moneyFormat(scope.row.averageSubscriptionPrice) }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('累计签约面积(㎡)')" align="center" prop="accumulatedContractedArea" width="180">
            <template slot-scope="scope">
              <span>{{ moneyFormat(scope.row.accumulatedContractedArea) }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('累计签约货值')+ $t('金额单位')" align="center" prop="accumulatedContractValue" width="180">
            <template slot-scope="scope">
              <span>{{ moneyFormat(scope.row.accumulatedContractValue, 'w') }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="200">
            <template slot-scope="scope">
              <el-button
                size="small"
                type="text"
                icon="el-icon-edit"
                @click="updateHandleDetail(scope.row)"
              >{{ $t('修改') }}</el-button>
              <el-button
                size="small"
                type="text"
                icon="el-icon-delete"
                @click="deleteHandleDetail(scope.$index)"
              >{{ $t('删除') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 添加或修改业态销售明细对话框 -->
        <el-dialog :title="$t('业态销售明细')" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
          <dealMonitoringDetailForm ref="dealMonitoringDetailForm" />
        </el-dialog>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="deal:monthlyMonitoring" />
    </div>
  </div>
</template>

<script>
    import { saveDealMonthlyMonitoring, getDealMonthlyMonitoring, getByDays, getCountByDays } from '@/api/deal/estate/monthlyMonitoring/dealMonthlyMonitoring'
    import dealMonitoringDetailForm from './dealMonitoringDetailForm.vue'
    export default {
      components: {
        dealMonitoringDetailForm
      },
        data() {
            return {
                // 表单参数
                form: {
                  dealId: this.$route.query.id,
                  // 业态销售明细
                  dealMonitoringDetailList: []
                },
                // 遮罩层
                loading: false,
                detailLoading: false,
              // 是否显示弹出层
              formOpen: false,
              // 业态类型字典
              typeFormatsOptions: [],
              // 亮灯分类字典
              classificationOfLightsOptions: [],
              // 总条数
              total: 0,
                // 表单校验
                rules: {
                days: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }, { validator: this.daysList }
                ],
                accumulatedLandCost: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                landCostAdjustmentItem: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                additionToLandPrice: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                totalAccumulatedExpenses: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                totalCumulativeCost: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                valueGoodsPushed: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                numberSetsPushedDisks: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                soldACycle: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                thisMonthSubscribeCycle: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                thisMonthSubscribeAverage: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                totalSubscription: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                totalContractAmount: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                accumulatedContractedArea: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                averageContractUnitPrice: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                accumulatedRecoveryFunds: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                totalLineCredit: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ]
                }
            }
        },
      watch: {
        'form.dealMonitoringDetailList': {
          handler(val) {
            this.form.totalSubscription = 0
            this.form.totalContractAmount = 0
            this.form.accumulatedContractedArea = 0
            this.form.averageContractUnitPrice = 0
            if (val != null) {
              val.forEach((e) => {
                // 已认购总额
                this.form.totalSubscription += e.cumulativeSubscriptionValue
                // 已签约总额
                this.form.totalContractAmount += e.accumulatedContractValue
                // 累计签约面积
                this.form.accumulatedContractedArea += e.accumulatedContractedArea
              })
              // 平均签约单价
              this.form.averageContractUnitPrice = this.form.totalContractAmount / this.form.accumulatedContractedArea
              if (isNaN(this.form.totalSubscription)) {
                this.form.totalSubscription = 0
              }
              if (isNaN(this.form.totalContractAmount)) {
                this.form.totalContractAmount = 0
              }
              if (isNaN(this.form.accumulatedContractedArea)) {
                this.form.accumulatedContractedArea = 0
              }
              if (isNaN(this.form.averageContractUnitPrice)) {
                this.form.averageContractUnitPrice = 0
              }
              if (!isFinite(this.form.averageContractUnitPrice)) {
                this.form.averageContractUnitPrice = 0
              }
            }
          },
          deep: true
        }
      },
      mounted() {
        this.$bus.$emit('async_done')
      },
        created() {
            this.getDicts('classification_of_lights').then(response => {
                this.classificationOfLightsOptions = response.data
            })
          this.getDicts('type_formats').then(response => {
            this.typeFormatsOptions = response.data
          })
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                if (data != null && data.id !== undefined) {
                    getDealMonthlyMonitoring(data.id).then(response => {
                        this.form = response.data
                        this.loading = false
                    })
                } else {
                    this.reset()
                    getByDays(this.form.dealId).then(response => {
                      if (response.data != null) {
                        this.form = response.data
                        this.form.id = undefined
                      }
                  })
                    this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,

                    dealId: this.$route.query.id,

                    days: undefined,

                    classificationOfLights: undefined,

                    accumulatedLandCost: undefined,

                    landCostAdjustmentItem: undefined,

                    additionToLandPrice: undefined,

                    totalAccumulatedExpenses: undefined,

                    totalCumulativeCost: undefined,

                    valueGoodsPushed: undefined,

                    numberSetsPushedDisks: undefined,

                    soldACycle: undefined,

                    thisMonthSubscribeCycle: undefined,

                    thisMonthSubscribeAverage: undefined,

                    totalSubscription: undefined,

                    totalContractAmount: undefined,

                    accumulatedContractedArea: undefined,

                    averageContractUnitPrice: undefined,

                    accumulatedRecoveryFunds: undefined,

                    totalLineCredit: undefined,

                    briefAnalysis: undefined,

                    redAndYellowDeal: undefined,

                    needCommunicate: undefined,

                    remark: undefined,

                    delFlag: undefined,

                    createBy: undefined,

                    createTime: undefined,

                    updateBy: undefined,

                    updateTime: undefined,
                  dealMonitoringDetailList: []
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm: function() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        saveDealMonthlyMonitoring(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                            this.loading = false
                        })
                    } else {
                       this.locationError(document)
                    }
                })
           },
          async daysList(rule, value, callback) {
            if (this.form.days != null) {
              var daysList = await getCountByDays(this.form.days, this.form.dealId, this.form.id)
              var aData = new Date()
              this.value = aData.getFullYear() + '-' + (aData.getMonth() + 1)
              if (new Date(this.form.days).getTime() === new Date(this.value).getTime() || new Date(this.form.days).getTime() > new Date(this.value).getTime()) {
                callback(new Error(this.$t('年月不可等于本月也不可比本月晚!')))
              } else if (daysList.data != null) {
                callback(new Error(this.$t('日期不能重复')))
              } else {
                callback()
              }
            } else {
              callback()
            }
          },
          // ----------------业态销售明细表---------------------------------------------------
          // 业态类型字典翻译
          typeFormatsFormat(row) {
            return this.selectDictLabel(this.typeFormatsOptions, row.typeFormats)
          },
          /** 新增按钮操作 */
          addHandleDetail() {
            this.formOpen = true
            this.$nextTick(() => {
              this.$refs.dealMonitoringDetailForm.initAdd()
            })
          },
          /** 修改按钮操作 */
          updateHandleDetail(row) {
            this.formOpen = true
            this.$nextTick(() => {
              // 调用form页面的 init 方法初始化数据
              this.$refs.dealMonitoringDetailForm.init(row)
            })
          },
          /** 删除按钮操作 */
          deleteHandleDetail(index) {
            this.form.dealMonitoringDetailList.splice(index, 1)
          }
          // DetailList(data) {
          //   data.id = undefined
          //   const obj = data
          //   //   {
          //   //   typeFormats: data.typeFormats,
          //   //
          //   //   totalSaleableArea: data.totalSaleableArea,
          //   //
          //   //   cumulativeSubscriptionArea: data.cumulativeSubscriptionArea,
          //   //
          //   //   cumulativeSubscriptionValue: data.cumulativeSubscriptionValue,
          //   //
          //   //   averageSubscriptionPrice: data.averageSubscriptionPrice,
          //   //
          //   //   subscriptionAreaMonth: data.subscriptionAreaMonth,
          //   //
          //   //   thisMonthValue: data.thisMonthValue,
          //   //
          //   //   thisMonthPrice: data.thisMonthPrice,
          //   //
          //   //   accumulatedContractedArea: data.accumulatedContractedArea,
          //   //
          //   //   accumulatedContractValue: data.accumulatedContractValue,
          //   //
          //   //   contractUnitPrice: data.contractUnitPrice,
          //   //
          //   //   contractAreaMonth: data.contractAreaMonth,
          //   //
          //   //   contractValueMonth: data.contractValueMonth,
          //   //
          //   //   contractUnitPriceMonth: data.accumulatedLandCost
          //   // }
          //     this.form.dealMonitoringDetailList.push(obj)
          // }
        }
    }
</script>
